<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>鹿茸库存管理系统 (LeanCloud版)</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
    <!-- LeanCloud JavaScript SDK -->
<script src="https://gitee.com/hymno1/leancloud-sdk/raw/master/av-min.js"></script>


    <style>
        /* 保持原有的CSS样式不变 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #2c3e50, #3498db);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
        }
        
        .content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
            padding: 30px;
        }
        
        .section {
            background: white;
            padding: 25px;
            border-radius: 15px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        
        .section:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.15);
        }
        
        .section h2 {
            color: #2c3e50;
            margin-bottom: 20px;
            font-size: 1.5em;
            border-bottom: 3px solid #3498db;
            padding-bottom: 10px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #34495e;
        }
        
        .form-group input, .form-group select {
            width: 100%;
            padding: 12px;
            border: 2px solid #ddd;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s ease, box-shadow 0.3s ease;
        }
        
        .form-group input:focus, .form-group select:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 10px rgba(52, 152, 219, 0.3);
        }
        
        .btn {
            background: linear-gradient(135deg, #3498db, #2980b9);
            color: white;
            padding: 12px 25px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
            font-weight: bold;
            transition: all 0.3s ease;
            margin-right: 10px;
            /* Ensure buttons are not full width by default unless specified in media query */
            width: auto; 
        }
        
        .btn:hover {
            background: linear-gradient(135deg, #2980b9, #1f5f8b);
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }
        
        .btn-export {
            background: linear-gradient(135deg, #27ae60, #229954);
        }
        
        .btn-export:hover {
            background: linear-gradient(135deg, #229954, #1e8449);
        }
        
        .btn-delete {
            background: linear-gradient(135deg, #e74c3c, #c0392b);
            padding: 8px 15px;
            font-size: 14px;
        }
        
        .btn-delete:hover {
            background: linear-gradient(135deg, #c0392b, #a93226);
        }
        
        .inventory-section {
            grid-column: span 2;
        }
        
        .table-container {
            overflow-x: auto; /* Allows horizontal scrolling for tables on small screens */
            margin-top: 20px;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }
        
        th, td {
            padding: 15px;
            text-align: left;
            border-bottom: 1px solid #ecf0f1;
        }
        
        th {
            background: linear-gradient(135deg, #34495e, #2c3e50);
            color: white;
            font-weight: bold;
            text-transform: uppercase;
            letter-spacing: 1px;
        }
        
        tr:hover {
            background-color: #f8f9fa;
            transition: background-color 0.3s ease;
        }
        
        .stats {
            display: grid;
            /* Changed to 1fr for single column by default, can be adjusted for larger screens if needed */
            grid-template-columns: 1fr; 
            gap: 15px;
            margin: 20px 0;
        }
        
        .stat-card {
            background: linear-gradient(135deg, #e74c3c, #c0392b);
            color: white;
            padding: 20px;
            border-radius: 12px;
            text-align: center;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }
        
        .stat-card h3 {
            font-size: 2em;
            margin-bottom: 5px;
        }
        
        .export-section {
            margin-top: 20px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 12px;
        }
        
        .export-buttons {
            display: flex;
            gap: 10px;
            flex-wrap: wrap; /* Allows buttons to wrap to next line if space is limited */
        }
        
        .message {
            padding: 12px;
            margin: 10px 0;
            border-radius: 8px;
            font-weight: bold;
        }
        
        .success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .auto-calc-hint {
            font-size: 12px;
            color: #666;
            margin-top: 5px;
            font-style: italic;
        }

        .pagination {
            display: flex;
           justify-content: center;
          align-items: center;
           gap: 10px;
           margin-top: 5px;
         padding: 0px;
     }

.pagination button {
    padding: 5px 5px;
    font-size: 12px;
}

.pagination span {
    font-weight: bold;
    color: #2c3e50;
}

        /* --- Mobile Responsive Styles --- */
        @media (max-width: 992px) { /* Adjusted breakpoint for tablets and larger phones */
            .content {
                /* Change to a single-column layout for tablets and below */
                grid-template-columns: 1fr;
            }
            .inventory-section {
                 /* Ensure inventory section also spans 1 column in this view */
                grid-column: span 1;
            }
        }


        @media (max-width: 768px) {
            body {
                padding: 10px; /* Reduce padding on smaller screens */
            }

            .header {
                padding: 20px;
            }

            .header h1 {
                font-size: 2em; /* Make header text smaller */
            }

            .content {
                padding: 15px;
                gap: 20px;
            }

            .section {
                padding: 15px; /* Reduce section padding */
            }

            .section h2 {
                font-size: 1.3em; /* Slightly smaller section titles */
            }

            .form-group input, .form-group select, .btn {
                font-size: 15px; /* Adjust font size for better readability */
                padding: 10px; /* Adjust padding for form elements */
            }
             .btn {
                margin-right: 5px; /* Reduce margin for buttons */
                margin-bottom: 10px; /* Add bottom margin for stacked buttons */
            }


            th, td {
                padding: 10px 8px; /* Reduce padding in table cells */
                font-size: 14px; /* Adjust table font size */
            }

            .stat-card h3 {
                font-size: 1.8em; /* Adjust stat card title */
            }
            .stat-card p {
                font-size: 0.9em; /* Adjust stat card paragraph */
            }

            .export-buttons {
                /* Allow buttons to stack vertically if needed */
                flex-direction: column;
                align-items: stretch; /* Make buttons take full width of container */
            }

            .export-buttons .btn {
                width: 100%; /* Make export buttons take full width */
                margin-right: 0; /* Remove right margin when stacked */
            }

            #backupFile {
                 /* Ensure file input is visible or styled appropriately for mobile */
                display: block;
                margin: 10px 0;
            }
        }

         @media (max-width: 480px) { /* Further adjustments for very small screens */
            .header h1 {
                font-size: 1.8em;
            }
            .section h2 {
                font-size: 1.2em;
            }
            .btn {
                font-size: 14px;
                padding: 8px 10px;
            }
             th, td {
                padding: 8px 5px;
                font-size: 13px;
            }
        }

    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🦌 鹿茸库存管理</h1>
        </div>
        
        <div class="content">
            <!-- 入库功能 -->
            <div class="section">
                <h2>📥 鹿茸入库</h2>
                <form id="instockForm">
                    <div class="form-group">
                        <label for="instockDate">入库时间:</label>
                        <input type="date" id="instockDate" required>
                    </div>
                    <div class="form-group">
                        <label for="antlerNumber">鹿茸号码:</label>
                        <input type="text" id="antlerNumber" placeholder="请输入鹿茸编号" required>
                    </div>
                    <div class="form-group">
                        <label for="antlerWeight">鹿茸重量 (克):</label>
                        <input type="number" id="antlerWeight" step="0.1" placeholder="请输入重量" required>
                    </div>
                    <button type="submit" class="btn">确认入库</button>
                </form>
                <div id="instockMessage"></div>
            </div>

            <!-- 出库功能 -->
            <div class="section">
                <h2>📤 鹿茸出库</h2>
                <form id="outstockForm">
                    <div class="form-group">
                        <label for="outstockDate">出库时间:</label>
                        <input type="date" id="outstockDate" required>
                    </div>
                    <div class="form-group">
                        <label for="outstockNumber">鹿茸号码:</label>
                        <select id="outstockNumber" required>
                            <option value="">请选择鹿茸号码</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="outstockWeight">出库重量 (克):</label>
                        <input type="number" id="outstockWeight" step="0.1" placeholder="请输入出库重量" required>
                    </div>
                    <div class="form-group">
                        <label for="unitPrice">售卖单价 (元/克):</label>
                        <input type="number" id="unitPrice" step="0.01" placeholder="请输入单价" required>
                    </div>
                    <div class="form-group">
                        <label for="totalAmount">售卖金额 (元):</label>
                        <input type="number" id="totalAmount" step="0.01" placeholder="可手动输入或自动计算" required>
                    </div>
                    <button type="submit" class="btn">确认出库</button>
                </form>
                <div id="outstockMessage"></div>
            </div>

            <!-- 库存显示 -->
            <div class="section inventory-section">
                <h2>📊 当前库存</h2>
                <div class="stats">
                    <div class="stat-card">
                        <h3 id="totalWeight">0</h3>
                        <p>总重量 (克)</p>
                    </div>
                </div>
                <div class="table-container">
                    <table id="inventoryTable">
                        <thead>
                            <tr>
                                <th>鹿茸号码</th>
                                <th>剩余重量 (克)</th>
                                <th>入库时间</th>
                                <th>状态</th>
                            </tr>
                        </thead>
                        <tbody id="inventoryTableBody">
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="pagination">
    <button id="prevInventoryPage" class="btn">上一页</button>
    <span id="inventoryPageInfo">第 1 页</span>
    <button id="nextInventoryPage" class="btn">下一页</button>
</div>

            <!-- 数据导出 -->
            <div class="section inventory-section">
                <h2>📋 数据导出</h2>
                <div class="export-section">
                    <h3>导出Excel表格</h3>
                    <div class="export-buttons">
                        <button class="btn btn-export" onclick="exportInstock()">导出入库记录</button>
                        <button class="btn btn-export" onclick="exportOutstock()">导出出库记录</button>
                        <button class="btn btn-export" onclick="exportInventory()">导出当前库存</button>
                        <button class="btn btn-export" onclick="exportAll()">导出所有数据</button>
                    </div>
                </div>
                
                <div class="export-section">
                    <h3>数据备份与恢复</h3>
                    <div class="export-buttons">
                        <button class="btn btn-export" onclick="exportBackup()">💾 导出数据备份</button>
                        <input type="file" id="backupFile" accept=".json" style="display: none;" onchange="importBackup(event)">
                        <button class="btn btn-export" onclick="document.getElementById('backupFile').click()">📂 导入数据备份</button>
                        <button class="btn" onclick="clearAllData()" style="background: linear-gradient(135deg, #e74c3c, #c0392b);">🗑️ 清空所有数据</button>
                    </div>
                    <p style="margin-top: 10px; color: #666; font-size: 14px;">
                        💡 提示：数据会自动保存到LeanCloud数据库
                    </p>
                </div>
                
                <!-- 查询功能 -->
                <div class="section inventory-section">
                    <h2>🔍 查询记录</h2>
                    <div class="form-group">
                        <label for="searchNumber">请输入鹿茸编号进行查询：</label>
                        <input type="text" id="searchNumber" placeholder="例如：A001" oninput="searchByNumber()">
                    </div>
                    <div class="table-container">
                        <h3>入库记录</h3>
                        <table>
                            <thead>
                                <tr>
                                    <th>入库时间</th>
                                    <th>鹿茸号码</th>
                                    <th>重量 (克)</th>
                                </tr>
                            </thead>
                            <tbody id="searchInstockResults"></tbody>
                        </table>
                    </div>
                    <div class="table-container">
                        <h3>出库记录</h3>
                        <table>
                            <thead>
                                <tr>
                                    <th>出库时间</th>
                                    <th>鹿茸号码</th>
                                    <th>重量 (克)</th>
                                    <th>单价 (元/克)</th>
                                    <th>金额 (元)</th>
                                </tr>
                            </thead>
                            <tbody id="searchOutstockResults"></tbody>
                        </table>
                    </div>
                </div>

                <!-- 历史记录表格 -->
                <div class="table-container">
                    <h3>入库记录</h3>
                    <table id="instockHistoryTable">
                        <thead>
                            <tr>
                                <th>入库时间</th>
                                <th>鹿茸号码</th>
                                <th>重量 (克)</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="instockHistoryBody">
                        </tbody>
                    </table>
                </div>
<div class="pagination">
    <button id="prevInstockPage" class="btn">上一页</button>
    <span id="instockPageInfo">第 1 页</span>
    <button id="nextInstockPage" class="btn">下一页</button>
</div>
                <div class="table-container">
                    <h3>出库记录</h3>
                    <table id="outstockHistoryTable">
                        <thead>
                            <tr>
                                <th>出库时间</th>
                                <th>鹿茸号码</th>
                                <th>重量 (克)</th>
                                <th>单价 (元/克)</th>
                                <th>金额 (元)</th>
                            </tr>
                        </thead>
                        <tbody id="outstockHistoryBody">
                        </tbody>
                    </table>
                </div>
                <div class="pagination">
    <button id="prevOutstockPage" class="btn">上一页</button>
    <span id="outstockPageInfo">第 1 页</span>
    <button id="nextOutstockPage" class="btn">下一页</button>
</div>
            </div>
        </div>
    </div>

    <script>
        // LeanCloud 配置 (请替换成您自己的 APP ID 和 APP KEY)
        const LEANCLOUD_APP_ID = 'SyC1jqSe1rXekq1Z5mzWcRC8-gzGzoHsz';
        const LEANCLOUD_APP_KEY = 'tobmkIdTdfnxZyRUZxnDIDEf';
        // 如果您的应用不是国际版，可能需要设置 serverURLs
       const LEANCLOUD_SERVER_URL = 'https://syc1jqse.lc-cn-n1-shared.com'; 

        AV.init({
            appId: LEANCLOUD_APP_ID,
            appKey: LEANCLOUD_APP_KEY,
             serverURL: LEANCLOUD_SERVER_URL // 如果需要，取消注释并设置
        });

        // LeanCloud Class 名称定义
        const InstockRecordClass = AV.Object.extend('InstockRecord');
        const OutstockRecordClass = AV.Object.extend('OutstockRecord');
        const InventoryItemClass = AV.Object.extend('InventoryItem');


        // 数据存储 (本地缓存)
        let instockRecords = [];
        let outstockRecords = [];
        let inventory = [];
        
        // 分页相关变量
        let currentInventoryPage = 1;
        let currentInstockPage = 1;
        let currentOutstockPage = 1;
        const itemsPerPage = 20;
        // 初始化
document.addEventListener('DOMContentLoaded', function() {
    // 从LeanCloud加载数据
    loadDataFromLeanCloud();

    // 设置默认时间为当前时间（只显示年月日）
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const dateStr = `${year}-${month}-${day}`;
    
    document.getElementById('instockDate').value = dateStr;
    document.getElementById('outstockDate').value = dateStr;
    document.getElementById('instockDate').type = 'date';
    document.getElementById('outstockDate').type = 'date';

    // 绑定事件
    document.getElementById('instockForm').addEventListener('submit', handleInstock);
    document.getElementById('outstockForm').addEventListener('submit', handleOutstock);
    document.getElementById('outstockWeight').addEventListener('input', calculateAmount);
    document.getElementById('unitPrice').addEventListener('input', calculateAmount);
});

        // 从LeanCloud加载数据
        async function loadDataFromLeanCloud() {
            try {
                // 加载入库记录
                const instockQuery = new AV.Query('InstockRecord');
                instockQuery.addAscending('date'); // 按日期升序排序
                const instockResults = await instockQuery.find();
                instockRecords = instockResults.map(obj => ({
                    id: obj.id, // LeanCloud objectId
                    date: obj.get('date'),
                    number: obj.get('number'),
                    weight: obj.get('weight')
                }));

                // 加载出库记录
                const outstockQuery = new AV.Query('OutstockRecord');
                outstockQuery.addAscending('date'); // 按日期升序排序
                const outstockResults = await outstockQuery.find();
                outstockRecords = outstockResults.map(obj => ({
                    id: obj.id,
                    date: obj.get('date'),
                    number: obj.get('number'),
                    weight: obj.get('weight'),
                    unitPrice: obj.get('unitPrice'),
                    totalAmount: obj.get('totalAmount'),
                    instockDate: obj.get('instockDate') 
                }));

                // 加载库存
                const inventoryQuery = new AV.Query('InventoryItem');
                inventoryQuery.addAscending('instockDate'); // 按入库日期升序排序
                const inventoryResults = await inventoryQuery.find();
                inventory = inventoryResults.map(obj => ({
                    id: obj.id,
                    number: obj.get('number'),
                    weight: obj.get('weight'),
                    originalWeight: obj.get('originalWeight'),
                    instockDate: obj.get('instockDate')
                }));

                updateDisplay();
            } catch (error) {
                console.error("从LeanCloud加载数据失败:", error);
                showMessage('instockMessage', '加载数据失败，请检查网络连接和LeanCloud配置', 'error');
            }
        }

        // 入库处理
        async function handleInstock(e) {
            e.preventDefault();
            
            const date = document.getElementById('instockDate').value;
            const number = document.getElementById('antlerNumber').value.trim();
            const weight = parseFloat(document.getElementById('antlerWeight').value);

            if (!date || !number || !weight || weight <= 0) {
                showMessage('instockMessage', '请填写所有必填项，重量必须大于0', 'error');
                return;
            }

            try {
                // 创建入库记录对象
                const instockRecord = new InstockRecordClass();
                instockRecord.set('date', date);
                instockRecord.set('number', number);
                instockRecord.set('weight', weight);
                const savedInstockRecord = await instockRecord.save();

                // 添加到本地数组
                instockRecords.push({
                    id: savedInstockRecord.id,
                    date: date,
                    number: number,
                    weight: weight
                });

                // 创建库存项目对象
                const inventoryItem = new InventoryItemClass();
                inventoryItem.set('number', number);
                inventoryItem.set('weight', weight);
                inventoryItem.set('originalWeight', weight);
                inventoryItem.set('instockDate', date);
                const savedInventoryItem = await inventoryItem.save();

                inventory.push({
                    id: savedInventoryItem.id,
                    number: number,
                    weight: weight,
                    originalWeight: weight,
                    instockDate: date
                });

                // 清空表单
                document.getElementById('instockForm').reset();
                const now = new Date();
                const localDateTime = new Date(now.getTime() - now.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
                document.getElementById('instockDate').value = localDateTime;

                showMessage('instockMessage', '入库成功！', 'success');
                updateDisplay();
            } catch (error) {
                console.error("入库操作失败:", error);
                showMessage('instockMessage', '入库失败，请检查网络或LeanCloud服务', 'error');
            }
        }
        
        // 删除入库记录 (及其关联数据)
        async function deleteInstockRecord(recordId) {
            const confirmed = await showCustomConfirm('确定要删除这条入库记录吗？\n注意：这将同时删除相关的库存和出库记录！');
            if (!confirmed) {
                return;
            }

            try {
                // 1. 获取要删除的入库记录的详细信息
                const instockRecordToDelete = instockRecords.find(r => r.id === recordId);
                if (!instockRecordToDelete) {
                    await showCustomAlert('未在本地找到对应的入库记录，请刷新后重试。');
                    return;
                }
                const antlerNumber = instockRecordToDelete.number;
                const originalInstockDate = instockRecordToDelete.date;

                // 2. 查找并准备删除关联的库存记录
                const inventoryQuery = new AV.Query('InventoryItem');
                inventoryQuery.equalTo('number', antlerNumber);
                inventoryQuery.equalTo('instockDate', originalInstockDate);
                const relatedInventoryItems = await inventoryQuery.find();
                
                // 3. 查找并准备删除关联的出库记录
                const outstockQuery = new AV.Query('OutstockRecord');
                outstockQuery.equalTo('number', antlerNumber);
                outstockQuery.equalTo('instockDate', originalInstockDate); // 假设出库记录也以此关联
                const relatedOutstockItems = await outstockQuery.find();

                // 4. 创建一个包含所有待删除对象的数组
                const objectsToDelete = [];
                const mainInstockObject = AV.Object.createWithoutData('InstockRecord', recordId);
                objectsToDelete.push(mainInstockObject);
                relatedInventoryItems.forEach(item => objectsToDelete.push(AV.Object.createWithoutData('InventoryItem', item.id)));
                relatedOutstockItems.forEach(item => objectsToDelete.push(AV.Object.createWithoutData('OutstockRecord', item.id)));

                // 5. 批量删除
                if (objectsToDelete.length > 0) {
                    await AV.Object.destroyAll(objectsToDelete);
                }

                // 6. 从本地数组中删除
                instockRecords = instockRecords.filter(record => record.id !== recordId);
                inventory = inventory.filter(item => !(item.number === antlerNumber && item.instockDate === originalInstockDate));
                outstockRecords = outstockRecords.filter(record => !(record.number === antlerNumber && record.instockDate === originalInstockDate));

                // 7. 更新显示
                updateDisplay();
                await showCustomAlert('入库记录及相关数据已成功删除！');

            } catch (error) {
                console.error("删除记录失败:", error);
                await showCustomAlert('删除记录失败: ' + error.message);
            }
        }

        // 出库处理
        async function handleOutstock(e) {
            e.preventDefault();
            
            const date = document.getElementById('outstockDate').value;
            const selectedInventoryId = document.getElementById('outstockNumber').value; // 这是 LeanCloud objectId
            const weightToOutstock = parseFloat(document.getElementById('outstockWeight').value);
            const unitPrice = parseFloat(document.getElementById('unitPrice').value);
            const totalAmount = parseFloat(document.getElementById('totalAmount').value);

            if (!date || !selectedInventoryId || !weightToOutstock || !unitPrice || !totalAmount || weightToOutstock <= 0 || unitPrice <= 0 || totalAmount <= 0) {
                showMessage('outstockMessage', '请填写所有必填项，数值必须大于0', 'error');
                return;
            }

            try {
                // 找到对应的库存项 (从本地缓存，因为LeanCloud ID是唯一的)
                const inventoryItemToUpdate = inventory.find(item => item.id === selectedInventoryId);
                if (!inventoryItemToUpdate || inventoryItemToUpdate.weight < weightToOutstock) {
                    showMessage('outstockMessage', '库存不足或未找到该库存项，无法出库', 'error');
                    return;
                }

                // 创建出库记录对象
                const outstockRecord = new OutstockRecordClass();
                outstockRecord.set('date', date);
                outstockRecord.set('number', inventoryItemToUpdate.number);
                outstockRecord.set('weight', weightToOutstock);
                outstockRecord.set('unitPrice', unitPrice);
                outstockRecord.set('totalAmount', totalAmount);
                outstockRecord.set('instockDate', inventoryItemToUpdate.instockDate); // 关联入库批次
                const savedOutstockRecord = await outstockRecord.save();

                // 添加到本地数组
                outstockRecords.push({
                    id: savedOutstockRecord.id,
                    date: date,
                    number: inventoryItemToUpdate.number,
                    weight: weightToOutstock,
                    unitPrice: unitPrice,
                    totalAmount: totalAmount,
                    instockDate: inventoryItemToUpdate.instockDate
                });

                // 更新库存
                const newWeight = inventoryItemToUpdate.weight - weightToOutstock;
                const lcInventoryItem = AV.Object.createWithoutData('InventoryItem', selectedInventoryId);

                if (newWeight <= 0.001) { // 使用一个小容差比较浮点数
                    // 如果库存为0或接近0，删除库存项
                    await lcInventoryItem.destroy();
                    inventory = inventory.filter(item => item.id !== selectedInventoryId);
                } else {
                    // 否则更新库存重量
                    lcInventoryItem.set('weight', newWeight);
                    await lcInventoryItem.save();
                    inventoryItemToUpdate.weight = newWeight; // 更新本地缓存
                }

                // 清空表单
                document.getElementById('outstockForm').reset();
                const now = new Date();
                const localDateTime = new Date(now.getTime() - now.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
                document.getElementById('outstockDate').value = localDateTime;

                showMessage('outstockMessage', '出库成功！', 'success');
                updateDisplay();
            } catch (error) {
                console.error("出库操作失败:", error);
                showMessage('outstockMessage', '出库失败，请检查网络或LeanCloud服务', 'error');
            }
        }

        // 计算总金额
        function calculateAmount() {
            const weight = parseFloat(document.getElementById('outstockWeight').value) || 0;
            const unitPrice = parseFloat(document.getElementById('unitPrice').value) || 0;
            
            if (weight > 0 && unitPrice > 0) {
                const totalAmount = weight * unitPrice;
                document.getElementById('totalAmount').value = totalAmount.toFixed(2);
            } else if (weight === 0 || unitPrice === 0) {
                document.getElementById('totalAmount').value = '';
            }
        }

        // 显示消息
        function showMessage(elementId, message, type) {
            const messageElement = document.getElementById(elementId);
            messageElement.innerHTML = `<div class="message ${type}">${message}</div>`;
            setTimeout(() => {
                messageElement.innerHTML = '';
            }, 3000);
        }
        
        // 分页函数
function getPaginatedItems(items, page) {
    const startIndex = (page - 1) * itemsPerPage;
    return items.slice(startIndex, startIndex + itemsPerPage);
}

// 更新分页信息显示
function updatePaginationInfo() {
    document.getElementById('inventoryPageInfo').textContent = 
        `第 ${currentInventoryPage} 页 / 共 ${Math.ceil(inventory.length / itemsPerPage)} 页`;
    document.getElementById('instockPageInfo').textContent = 
        `第 ${currentInstockPage} 页 / 共 ${Math.ceil(instockRecords.length / itemsPerPage)} 页`;
    document.getElementById('outstockPageInfo').textContent = 
        `第 ${currentOutstockPage} 页 / 共 ${Math.ceil(outstockRecords.length / itemsPerPage)} 页`;
}

        // 更新显示
        function updateDisplay() {
            updateInventoryTable();
            updateHistoryTables();
            updateOutstockOptions();
            updateStats();
            updatePaginationInfo();
        }

        // 更新库存表格
        function updateInventoryTable() {
    const tbody = document.getElementById('inventoryTableBody');
    tbody.innerHTML = '';
    
    const paginatedInventory = getPaginatedItems([...inventory].sort((a, b) => 
        new Date(a.instockDate) - new Date(b.instockDate)), currentInventoryPage);
    
    paginatedInventory.forEach(item => {
        const row = tbody.insertRow();
        row.innerHTML = `
            <td>${item.number}</td>
            <td>${item.weight.toFixed(1)}</td>
            <td>${new Date(item.instockDate).toLocaleDateString('zh-CN')}</td>
            <td><span style="color: #27ae60; font-weight: bold;">在库</span></td>
        `;
    });
}

        // 更新历史记录表格
function updateHistoryTables() {
    const instockBody = document.getElementById('instockHistoryBody');
    instockBody.innerHTML = '';
    
    const paginatedInstock = getPaginatedItems([...instockRecords].sort((a,b) => 
        new Date(b.date) - new Date(a.date)), currentInstockPage);
    
    paginatedInstock.forEach(record => {
        const row = instockBody.insertRow();
        row.innerHTML = `
            <td>${new Date(record.date).toLocaleDateString('zh-CN')}</td>
            <td>${record.number}</td>
            <td>${record.weight.toFixed(1)}</td>
            <td><button class="btn btn-delete" onclick="deleteInstockRecord('${record.id}')">删除</button></td>
        `;
    });

    const outstockBody = document.getElementById('outstockHistoryBody');
    outstockBody.innerHTML = '';
    
    const paginatedOutstock = getPaginatedItems([...outstockRecords].sort((a,b) => 
        new Date(b.date) - new Date(a.date)), currentOutstockPage);
    
    paginatedOutstock.forEach(record => {
        const row = outstockBody.insertRow();
        row.innerHTML = `
            <td>${new Date(record.date).toLocaleDateString('zh-CN')}</td>
            <td>${record.number}</td>
            <td>${record.weight.toFixed(1)}</td>
            <td>${record.unitPrice.toFixed(2)}</td>
            <td>${record.totalAmount.toFixed(2)}</td>
        `;
    });
}

// 添加分页按钮事件监听
document.addEventListener('DOMContentLoaded', function() {
    // ...其他初始化代码...
    
    // 分页按钮事件
   // 库存表格分页按钮
    document.getElementById('prevInventoryPage').addEventListener('click', () => {
    if (currentInventoryPage > 1) {
        currentInventoryPage--;
        updateInventoryTable();
        updatePaginationInfo();
        // 滚动到库存表格顶部
        document.getElementById('inventoryTable').scrollIntoView({
            behavior: 'smooth',
            block: 'start'
        });
    }
});

     document.getElementById('nextInventoryPage').addEventListener('click', () => {
    const totalPages = Math.ceil(inventory.length / itemsPerPage);
    if (currentInventoryPage < totalPages) {
        currentInventoryPage++;
        updateInventoryTable();
        updatePaginationInfo();
        // 滚动到库存表格顶部
        document.getElementById('inventoryTable').scrollIntoView({
            behavior: 'smooth',
            block: 'start'
        });
    }
});

// 入库历史分页按钮
document.getElementById('prevInstockPage').addEventListener('click', () => {
    if (currentInstockPage > 1) {
        currentInstockPage--;
        updateHistoryTables();
        updatePaginationInfo();
        // 滚动到入库历史表格顶部
        document.getElementById('instockHistoryTable').scrollIntoView({
            behavior: 'smooth',
            block: 'start'
        });
    }
});

document.getElementById('nextInstockPage').addEventListener('click', () => {
    const totalPages = Math.ceil(instockRecords.length / itemsPerPage);
    if (currentInstockPage < totalPages) {
        currentInstockPage++;
        updateHistoryTables();
        updatePaginationInfo();
        // 滚动到入库历史表格顶部
        document.getElementById('instockHistoryTable').scrollIntoView({
            behavior: 'smooth',
            block: 'start'
        });
    }
});

// 出库历史分页按钮
document.getElementById('prevOutstockPage').addEventListener('click', () => {
    if (currentOutstockPage > 1) {
        currentOutstockPage--;
        updateHistoryTables();
        updatePaginationInfo();
        // 滚动到出库历史表格顶部
        document.getElementById('outstockHistoryTable').scrollIntoView({
            behavior: 'smooth',
            block: 'start'
        });
    }
});

document.getElementById('nextOutstockPage').addEventListener('click', () => {
    const totalPages = Math.ceil(outstockRecords.length / itemsPerPage);
    if (currentOutstockPage < totalPages) {
        currentOutstockPage++;
        updateHistoryTables();
        updatePaginationInfo();
        // 滚动到出库历史表格顶部
        document.getElementById('outstockHistoryTable').scrollIntoView({
            behavior: 'smooth',
            block: 'start'
        });
    }
});
});



        // 更新出库选项
        function updateOutstockOptions() {
            const select = document.getElementById('outstockNumber');
            select.innerHTML = '<option value="">请选择鹿茸号码</option>';
            // inventory 数组已经按 instockDate 排序
            [...inventory].sort((a, b) => new Date(a.instockDate) - new Date(b.instockDate)).forEach(item => {
                const option = document.createElement('option');
                option.value = item.id; // LeanCloud objectId
                const instockDateStr = new Date(item.instockDate).toLocaleDateString('zh-CN');
                option.textContent = `${item.number} - ${instockDateStr} (库存: ${item.weight.toFixed(1)}克)`;
                select.appendChild(option);
            });
        }

        // 更新统计数据
        function updateStats() {
            const totalWeight = inventory.reduce((sum, item) => sum + item.weight, 0);
            document.getElementById('totalWeight').textContent = totalWeight.toFixed(1);
        }

        // Excel导出功能 (数据源是本地数组，排序已在显示时处理)
        function exportInstock() {
            if (instockRecords.length === 0) {
                showCustomAlert('没有入库记录可导出');
                return;
            }
            const data = [...instockRecords].sort((a,b) => new Date(a.date) - new Date(b.date)).map(record => ({
                '入库时间': new Date(record.date).toLocaleString('zh-CN'),
                '鹿茸号码': record.number,
                '重量(克)': record.weight
            }));
            const ws = XLSX.utils.json_to_sheet(data);
            const wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, '入库记录');
            XLSX.writeFile(wb, `鹿茸入库记录_${new Date().toISOString().slice(0, 10)}.xlsx`);
        }

        function exportOutstock() {
            if (outstockRecords.length === 0) {
                showCustomAlert('没有出库记录可导出');
                return;
            }
            const data = [...outstockRecords].sort((a,b) => new Date(a.date) - new Date(b.date)).map(record => ({
                '出库时间': new Date(record.date).toLocaleString('zh-CN'),
                '鹿茸号码': record.number,
                '重量(克)': record.weight,
                '单价(元/克)': record.unitPrice,
                '金额(元)': record.totalAmount,
                '入库批次': new Date(record.instockDate).toLocaleDateString('zh-CN')
            }));
            const ws = XLSX.utils.json_to_sheet(data);
            const wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, '出库记录');
            XLSX.writeFile(wb, `鹿茸出库记录_${new Date().toISOString().slice(0, 10)}.xlsx`);
        }

        function exportInventory() {
            if (inventory.length === 0) {
                showCustomAlert('没有库存数据可导出');
                return;
            }
            const data = [...inventory].sort((a,b) => new Date(a.instockDate) - new Date(b.instockDate)).map(item => ({
                '鹿茸号码': item.number,
                '剩余重量(克)': item.weight,
                '入库时间': new Date(item.instockDate).toLocaleString('zh-CN'),
                '状态': '在库'
            }));
            const ws = XLSX.utils.json_to_sheet(data);
            const wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, '当前库存');
            XLSX.writeFile(wb, `鹿茸库存_${new Date().toISOString().slice(0, 10)}.xlsx`);
        }

  function exportAll() {
    const wb = XLSX.utils.book_new();
    let hasData = false;

    // 导出入库记录
    if (instockRecords.length > 0) {
        const instockData = [...instockRecords]
            .sort((a, b) => new Date(a.date) - new Date(b.date))
            .map(record => ({
                '入库时间': new Date(record.date).toLocaleString('zh-CN'),
                '鹿茸号码': record.number,
                '重量(克)': record.weight
            }));
        const instockWs = XLSX.utils.json_to_sheet(instockData);
        XLSX.utils.book_append_sheet(wb, instockWs, '入库记录');
        hasData = true;
    }

    // 导出出库记录
    if (outstockRecords.length > 0) {
        const outstockData = [...outstockRecords]
            .sort((a, b) => new Date(a.date) - new Date(b.date))
            .map(record => ({
                '出库时间': new Date(record.date).toLocaleString('zh-CN'),
                '鹿茸号码': record.number,
                '重量(克)': record.weight,
                '单价(元/克)': record.unitPrice,
                '金额(元)': record.totalAmount,
                '入库批次': new Date(record.instockDate).toLocaleDateString('zh-CN')
            }));
        const outstockWs = XLSX.utils.json_to_sheet(outstockData);
        XLSX.utils.book_append_sheet(wb, outstockWs, '出库记录');
        hasData = true;
    }

    // 导出当前库存
    if (inventory.length > 0) {
        const inventoryData = [...inventory]
            .sort((a, b) => new Date(a.instockDate) - new Date(b.instockDate))
            .map(item => ({
                '鹿茸号码': item.number,
                '剩余重量(克)': item.weight,
                '入库时间': new Date(item.instockDate).toLocaleString('zh-CN'),
                '状态': item.weight > 0 ? '在库' : '已出完'
            }));
        const inventoryWs = XLSX.utils.json_to_sheet(inventoryData);
        XLSX.utils.book_append_sheet(wb, inventoryWs, '当前库存');
        hasData = true;
    }

    if (!hasData) {
        showCustomAlert('没有数据可导出');
        return;
    }

    XLSX.writeFile(wb, `鹿茸管理系统完整数据_${new Date().toISOString().slice(0, 10)}.xlsx`);
}

        // 数据备份功能 (LeanCloud)
        async function exportBackup() {
            try {
                const instockQuery = new AV.Query('InstockRecord');
                const outstockQuery = new AV.Query('OutstockRecord');
                const inventoryQuery = new AV.Query('InventoryItem');
                
                // 为了保证数据完整性，一次性获取所有数据（LeanCloud默认分页，大数据量可能需要处理分页）
                instockQuery.limit(1000); // 设置一个较大的limit，实际应用中可能需要分页
                outstockQuery.limit(1000);
                inventoryQuery.limit(1000);

                const [instockDataLC, outstockDataLC, inventoryDataLC] = await Promise.all([
                    instockQuery.find(),
                    outstockQuery.find(),
                    inventoryQuery.find()
                ]);

                const backupData = {
                    instock: instockDataLC.map(obj => obj.toJSON()), // toJSON() 获取包括objectId在内的所有属性
                    outstock: outstockDataLC.map(obj => obj.toJSON()),
                    inventory: inventoryDataLC.map(obj => obj.toJSON()),
                    exportTime: new Date().toISOString(),
                    version: '1.1-lc' // LeanCloud version
                };

                const dataStr = JSON.stringify(backupData, null, 2);
                const dataUri = 'data:application/json;charset=utf-8,' + encodeURIComponent(dataStr);
                const exportName = `鹿茸库存备份_LeanCloud_${new Date().toISOString().slice(0, 10)}.json`;
                const linkElement = document.createElement('a');
                linkElement.setAttribute('href', dataUri);
                linkElement.setAttribute('download', exportName);
                linkElement.click();
            } catch (error) {
                console.error("导出LeanCloud备份失败:", error);
                await showCustomAlert('导出备份失败: ' + error.message);
            }
        }

        // 数据恢复功能 (LeanCloud)
        async function importBackup(event) {
            const file = event.target.files[0];
            if (!file) return;
            if (!file.name.endsWith('.json')) {
                await showCustomAlert('请选择JSON格式的备份文件'); return;
            }

            const reader = new FileReader();
            reader.onload = async function(e) {
                try {
                    const backupData = JSON.parse(e.target.result);
                    if (!backupData.instock || !backupData.outstock || !backupData.inventory || !backupData.version) {
                        throw new Error('备份文件格式不正确或版本信息缺失');
                    }
                    
                    const confirmed = await showCustomConfirm('导入备份数据将覆盖当前所有LeanCloud数据，确定要继续吗？');
                    if (confirmed) {
                        await clearAllData(true); // 清空云端数据 (silent=true)
                        
                        const objectsToSave = [];
                        backupData.instock.forEach(record => {
                            const obj = new InstockRecordClass();
                            // 不设置objectId，让LeanCloud自动生成新的
                            for (const key in record) {
                                if (key !== 'objectId' && key !== 'createdAt' && key !== 'updatedAt' && key !== 'ACL') {
                                    obj.set(key, record[key]);
                                }
                            }
                            objectsToSave.push(obj);
                        });
                        backupData.outstock.forEach(record => {
                             const obj = new OutstockRecordClass();
                             for (const key in record) {
                                if (key !== 'objectId' && key !== 'createdAt' && key !== 'updatedAt' && key !== 'ACL') {
                                    obj.set(key, record[key]);
                                }
                            }
                            objectsToSave.push(obj);
                        });
                        backupData.inventory.forEach(record => {
                            const obj = new InventoryItemClass();
                             for (const key in record) {
                                if (key !== 'objectId' && key !== 'createdAt' && key !== 'updatedAt' && key !== 'ACL') {
                                    obj.set(key, record[key]);
                                }
                            }
                            objectsToSave.push(obj);
                        });

                        if (objectsToSave.length > 0) {
                            await AV.Object.saveAll(objectsToSave);
                        }
                        
                        await loadDataFromLeanCloud(); // 重新加载数据
                        await showCustomAlert('数据导入成功！');
                    }
                } catch (error) {
                    console.error("导入LeanCloud备份失败:", error);
                    await showCustomAlert('导入失败：' + error.message);
                }
            };
            reader.readAsText(file);
            event.target.value = ''; // 清空文件选择器
        }

        // 搜索功能 (LeanCloud)
        async function searchByNumber() {
            const keyword = document.getElementById('searchNumber').value.trim();
            const instockBody = document.getElementById('searchInstockResults');
            const outstockBody = document.getElementById('searchOutstockResults');
            instockBody.innerHTML = '';
            outstockBody.innerHTML = '';

            if (!keyword) return;

            try {
                const instockQuery = new AV.Query('InstockRecord');
                instockQuery.equalTo('number', keyword);
                instockQuery.addDescending('date'); // 按日期降序

                const outstockQuery = new AV.Query('OutstockRecord');
                outstockQuery.equalTo('number', keyword);
                outstockQuery.addDescending('date'); // 按日期降序

                const [instockResults, outstockResults] = await Promise.all([
                    instockQuery.find(),
                    outstockQuery.find()
                ]);

                instockResults.forEach(obj => {
                    const data = obj.attributes; // .attributes 包含所有数据
                    const row = instockBody.insertRow();
                    row.innerHTML = `
                        <td>${new Date(data.date).toLocaleString('zh-CN')}</td>
                        <td>${data.number}</td>
                        <td>${data.weight.toFixed(1)}</td>
                    `;
                });

                outstockResults.forEach(obj => {
                    const data = obj.attributes;
                    const row = outstockBody.insertRow();
                    row.innerHTML = `
                        <td>${new Date(data.date).toLocaleString('zh-CN')}</td>
                        <td>${data.number}</td>
                        <td>${data.weight.toFixed(1)}</td>
                        <td>${data.unitPrice.toFixed(2)}</td>
                        <td>${data.totalAmount.toFixed(2)}</td>
                    `;
                });
                
                if (instockResults.length === 0 && outstockResults.length === 0) {
                    showMessage('instockMessage', '未找到编号为 "' + keyword + '" 的记录', 'error'); 
                }

            } catch (error) {
                console.error("LeanCloud搜索失败:", error);
                showMessage('instockMessage', '搜索失败，请检查网络或LeanCloud服务', 'error');
            }
        }

        // 清空所有数据 (LeanCloud)
        async function clearAllData(silent = false) {
            let confirmed = silent;
            if (!silent) {
                 confirmed = await showCustomConfirm('确定要清空所有LeanCloud数据吗？此操作不可恢复！');
            }
            if (!confirmed) return;

            try {
                const classNames = ['InstockRecord', 'OutstockRecord', 'InventoryItem'];
                const promises = classNames.map(async (className) => {
                    let itemsToDelete;
                    do {
                        const query = new AV.Query(className);
                        query.limit(100); // LeanCloud批量删除上限通常是100或1000，具体看文档
                        itemsToDelete = await query.find();
                        if (itemsToDelete.length > 0) {
                            await AV.Object.destroyAll(itemsToDelete);
                        }
                    } while (itemsToDelete.length > 0);
                });
                
                await Promise.all(promises);
                
                instockRecords = [];
                outstockRecords = [];
                inventory = [];
                
                if (!silent) {
                    await showCustomAlert('所有LeanCloud数据已清空！');
                }
                updateDisplay();
            } catch (error) {
                console.error("清空LeanCloud数据失败:", error);
                 if (!silent) {
                    await showCustomAlert('清空数据失败: ' + error.message);
                 }
            }
        }

        // --- Custom Alert and Confirm (保持不变) ---
        function showCustomAlert(message) {
            return new Promise((resolve) => {
                const alertModal = document.createElement('div');
                alertModal.style.cssText = `
                    position: fixed; top: 0; left: 0; width: 100%; height: 100%;
                    background-color: rgba(0,0,0,0.5); display: flex;
                    justify-content: center; align-items: center; z-index: 1000; padding: 15px;
                `;
                const alertBox = document.createElement('div');
                alertBox.style.cssText = `
                    background-color: white; padding: 25px; border-radius: 10px;
                    box-shadow: 0 5px 15px rgba(0,0,0,0.3); text-align: center; max-width: 90%;
                `;
                const messageP = document.createElement('p');
                messageP.textContent = message;
                messageP.style.marginBottom = '20px';
                messageP.style.fontSize = '16px';
                const closeButton = document.createElement('button');
                closeButton.textContent = '确定';
                closeButton.className = 'btn';
                closeButton.style.marginRight = '0';
                closeButton.onclick = () => {
                    document.body.removeChild(alertModal);
                    resolve(true);
                };
                alertBox.appendChild(messageP);
                alertBox.appendChild(closeButton);
                alertModal.appendChild(alertBox);
                document.body.appendChild(alertModal);
            });
        }
        function showCustomConfirm(message) {
            return new Promise((resolve) => {
                const confirmModal = document.createElement('div');
                confirmModal.style.cssText = `
                    position: fixed; top: 0; left: 0; width: 100%; height: 100%;
                    background-color: rgba(0,0,0,0.5); display: flex;
                    justify-content: center; align-items: center; z-index: 1000; padding: 15px;
                `;
                const confirmBox = document.createElement('div');
                confirmBox.style.cssText = `
                    background-color: white; padding: 25px; border-radius: 10px;
                    box-shadow: 0 5px 15px rgba(0,0,0,0.3); text-align: center; max-width: 90%;
                `;
                const messageP = document.createElement('p');
                messageP.innerHTML = message.replace(/\n/g, '<br>');
                messageP.style.marginBottom = '20px';
                messageP.style.fontSize = '16px';
                const yesButton = document.createElement('button');
                yesButton.textContent = '确定';
                yesButton.className = 'btn';
                yesButton.style.marginRight = '10px';
                const noButton = document.createElement('button');
                noButton.textContent = '取消';
                noButton.className = 'btn';
                noButton.style.background = 'linear-gradient(135deg, #95a5a6, #7f8c8d)';
                yesButton.onclick = () => {
                    document.body.removeChild(confirmModal);
                    resolve(true);
                };
                noButton.onclick = () => {
                    document.body.removeChild(confirmModal);
                    resolve(false);
                };
                confirmBox.appendChild(messageP);
                confirmBox.appendChild(yesButton);
                confirmBox.appendChild(noButton);
                confirmModal.appendChild(confirmBox);
                document.body.appendChild(confirmModal);
            });
        }
    </script>
</body>
</html>
